<script setup>
import { getUserOrder, updateOrderStatus } from '@/apis/order';
import { onMounted, ref, watch } from 'vue';
import { ElMessage, ElEmpty, ElTabs, ElTabPane, ElPagination } from 'element-plus';
import { useUserStore } from "@/stores/userStore";

const userStore = useUserStore();

// Tab 列表及状态映射
const tabTypes = [
  { name: "all", label: "全部订单", orderState: 0 },
  { name: "deliver", label: "待发货", orderState: 1 },
  { name: "receive", label: "已发货", orderState: 2 },
  { name: "complete", label: "已完成", orderState: 3 }
];

// 后端状态码与前端数字的映射
const orderStatusMapping = {
  "待发货": 1,
  "已发货": 2,
  "已收货": 3,
};

// 前端数字与显示标签的映射
const orderStateMap = {
  0: '全部订单',
  1: '待发货',
  2: '已发货',
  3: '已收货',
};

// 订单列表和其他状态
const orderList = ref([]);
const params = ref({
  userId: userStore.userInfo.userId || 1, // 如果从 store 获取不到 userId，则使用默认值
  orderState: 0,
  page: 1,
  pageSize: 4
});
const total = ref(0);
const loading = ref(false);
const error = ref(null);

// 当前激活的 Tab (改为字符串)
const activeTab = ref("all");

// 格式化时间
const formatDate = (time) => {
  const date = new Date(time);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 获取订单列表
const getOrderList = async () => {
  try {
    loading.value = true;
    console.log('Fetching orders with params:', JSON.stringify(params.value)); // 日志输出请求参数
    const res = await getUserOrder(params.value);
    
    if (res.code === 1) { // 假设 code 为 1 表示成功
      orderList.value = res.data.orders.map(order => ({
        ...order,
        // 将后端的状态转换为前端使用的数字
        orderState: orderStatusMapping[order.orderStatus] || 0,
        // 设置用于显示的标签
        orderStatusLabel: orderStateMap[orderStatusMapping[order.orderStatus]] || '未知状态',
        products: order.products.map(product => ({...product, quantity: product.quantity || 1})) // 确保有数量信息
      }));
      
      // 使用后端提供的总数
      total.value = res.data.total;
      console.log('Fetched total orders:', total.value); // 日志输出总订单数
      error.value = null;
    } else {
      throw new Error('获取订单列表失败');
    }
  } catch (err) {
    error.value = '获取订单列表失败，请稍后再试';
    ElMessage.error('获取订单列表失败，请稍后再试');
    console.error('Error fetching order list:', err);
  } finally {
    loading.value = false;
  }
};

// 监听 Tab 切换
watch(activeTab, (newTabName) => {
  const selectedTab = tabTypes.find(tab => tab.name === newTabName);
  if (selectedTab) {
    params.value.orderState = selectedTab.orderState;
    params.value.page = 1; // 切换 Tab 时重置页数
    console.log('Tab changed to:', newTabName, 'with orderState:', params.value.orderState); // 调试信息
    getOrderList();
  }
}, { immediate: true });

onMounted(() => getOrderList());

// 页数切换
const pageChange = (page) => {
  console.log('Page change to:', page); // 日志输出新页码
  params.value.page = page;
  getOrderList();
};

// 确认收货
const confirmReceipt = async (order) => {
  try {
    const confirm = window.confirm(`确定要将订单 #${order.orderId} 已收货吗？`);
    if (!confirm) return;

    // 构建 OrderDto 对象
    const orderDto = {
      orderId: order.orderId,
      orderStatus: "已收货",
      paymentMethod: order.paymentMethod 
    };

    // 发送请求到后端更新订单状态
    console.log('Confirm receipt for order:', orderDto); // 日志输出
    const response = await updateOrderStatus(orderDto);

    if (response.code === 1) { 
      ElMessage.success('确认收货成功');
     
      order.orderState = 3;
      order.orderStatusLabel = '已收货';
      // 或者重新加载订单列表
      getOrderList();
    } else {
      throw new Error('服务器返回错误信息');
    }
  } catch (error) {
    ElMessage.error('确认收货失败，请稍后再试');
    console.error('Error confirming receipt:', error);
  }
};
</script>

<template>
  <div class="order-container">
    <el-tabs v-model="activeTab" type="border-card">
      <!-- Tab 切换 -->
      <el-tab-pane v-for="item in tabTypes" :key="item.name" :label="item.label" :name="item.name"></el-tab-pane>

      <div class="main-container">
        <!-- 加载中 -->
        <div v-if="loading" class="loading-container">
          <p>正在加载...</p>
        </div>

        <!-- 错误信息 -->
        <div v-else-if="error" class="error-container">
          <p>{{ error }}</p>
        </div>

        <!-- 暂无数据 -->
        <div v-else-if="orderList.length === 0" class="holder-container">
          <el-empty description="暂无订单数据" />
        </div>

        <!-- 订单列表 -->
        <div v-else>
          <div class="order-item" v-for="order in orderList" :key="order.orderId">
            <div class="head">
              <span>订单编号：{{ order.orderId }}</span>
              <span>下单时间：{{ formatDate(order.orderTime) }}</span>
              <span>支付方式：{{ order.paymentMethod }}</span>
              <span>订单状态：{{ order.orderStatusLabel }}</span>
            </div>
            <div class="body">
              <div class="column goods">
                <ul>
                  <li v-for="product in order.products" :key="product.productName">
                    <a class="image" href="javascript:;">
                      <img :src="product.productImage" alt="" />
                    </a>
                    <div class="info">
                      <p class="name ellipsis-2">{{ product.productName }}</p>
                      <p class="attr ellipsis">颜色: {{ product.productColor }}; 尺寸: {{ product.productSize }}</p>
                    </div>
                    <div class="price">¥{{ product.unitPrice?.toFixed(2) }}</div>
                    <div class="count">x{{ product.quantity }}</div>
                  </li>
                </ul>
              </div>
              <div class="column state">
                <p v-if="order.recipientAddress">收货地址：{{ order.recipientAddress }}</p>
                <p v-else>收货地址：未提供</p>
              </div>
              <div class="column amount">
                <p class="red">总金额：¥{{ order.totalPrice?.toFixed(2) }}</p>
              </div>
              <div class="column action">
                <p v-if="order.orderState === 2">
                  <a href="javascript:;" @click="confirmReceipt(order)">确认收货</a>
                </p>
              </div>
            </div>
          </div>
          <!-- 分页 -->
          <div class="pagination-container">
            <!-- 显示当前页码 -->
            <p v-if="total > 0">当前是第 {{ params.page }} 页</p>
            
            <!-- 分页控件 -->
            <el-pagination
              background
              layout="prev, next"
              :total="total"
              :page-size="params.pageSize"
              v-model:current-page="params.page"  
              @current-change="pageChange"
            />
          </div>
        </div>
      </div>
    </el-tabs>
  </div>
</template>

<style scoped lang="scss">
.order-container {
  padding: 10px 20px;

  .pagination-container {
    display: flex;
    justify-content: center;
  }

  .main-container {
    min-height: 500px;

    .holder-container {
      min-height: 500px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.order-item {
  margin-bottom: 20px;
  border: 1px solid #f5f5f5;

  .head {
    height: 50px;
    line-height: 50px;
    background: #f5f5f5;
    padding: 0 20px;
    overflow: hidden;

    span {
      margin-right: 20px;

      &.down-time {
        margin-right: 0;
        float: right;

        i {
          vertical-align: middle;
          margin-right: 3px;
        }

        b {
          vertical-align: middle;
          font-weight: normal;
        }
      }
    }

    .del {
      margin-right: 0;
      float: right;
      color: #999;
    }
  }

  .body {
    display: flex;
    align-items: stretch;

    .column {
      border-left: 1px solid #f5f5f5;
      text-align: center;
      padding: 20px;

      >p {
        padding-top: 10px;
      }

      &:first-child {
        border-left: none;
      }

      &.goods {
        flex: 1;
        padding: 0;
        align-self: center;

        ul {
          li {
            border-bottom: 1px solid #f5f5f5;
            padding: 10px;
            display: flex;

            &:last-child {
              border-bottom: none;
            }

            .image {
              width: 70px;
              height: 70px;
              border: 1px solid #f5f5f5;
            }

            .info {
              width: 220px;
              text-align: left;
              padding: 0 10px;

              p {
                margin-bottom: 5px;

                &.name {
                  height: 38px;
                }

                &.attr {
                  color: #999;
                  font-size: 12px;

                  span {
                    margin-right: 5px;
                  }
                }
              }
            }

            .price {
              width: 100px;
            }

            .count {
              width: 80px;
            }
          }
        }
      }

      &.state {
        width: 120px;

        .green {
          color: $xtxColor;
        }
      }

      &.amount {
        width: 200px;

        .red {
          color: $priceColor;
        }
      }

      &.action {
        width: 140px;

        a {
          display: block;

          &:hover {
            color: $xtxColor;
          }
        }
      }
    }
  }
}
</style>